package net.pimpas.transformation.xml.xslt.serviceprovider;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URL;

import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import net.pimpas.core.configuration.exception.ConfigurationException;
import net.pimpas.core.serviceprovider.ServiceProviderAnnotation;
import net.pimpas.core.serviceprovider.instancetype.ServiceProviderInstanceType;
import net.pimpas.transformation.serviceprovider.exception.TransformationServiceProviderException;

@ServiceProviderAnnotation(
		instanceType=ServiceProviderInstanceType.NORMAL, 
		serviceProviderType=XsltTransformationServiceProvider.class
)
public class XsltTransformationServiceProviderImpl implements XsltTransformationServiceProvider {

	public ObjectInputStream createObjectInputStream(Reader arg0) throws TransformationServiceProviderException {
		return null;
	}

	public ObjectOutputStream createObjectOutputStream(Writer arg0) throws TransformationServiceProviderException {
		return null;
	}

	public String from(String arg0, Object... parameters) throws TransformationServiceProviderException {
		return null;
	}

	public String to(String arg0, Object... parameters) throws TransformationServiceProviderException {
		// get xslt url
		URL url = (URL) parameters[0];
		
		try{
			InputStream xsl = url.openStream();					 
			TransformerFactory tFactory = TransformerFactory.newInstance();
			Transformer transformer = tFactory.newTransformer(new StreamSource(xsl));
			StringWriter swriter = new StringWriter(); 
			
			Result xmlt = new StreamResult(swriter);
			transformer.transform(new StreamSource(new StringReader(arg0)),xmlt);
			
			return swriter.toString();
		}catch(Exception e){
			throw new TransformationServiceProviderException(e);
		}
	}

	public void config() throws ConfigurationException {
		
	}
	
	public boolean isTerminated() {
		return false;
	}
}